<!--
 * @Author: zhao 13370229059@163.com
 * @Date: 2024-04-13 22:32:10
 * @LastEditors: zhao 13370229059@163.com
 * @LastEditTime: 2024-12-16 22:09:00
 * @FilePath: \dance\pages\index\index2Compontents\main.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <flow :data="ajax.list" @onScroll="onScroll" :top="props.top" @scrolltolower="scrolltolower"></flow>
  <uv-toast ref="toastRef"></uv-toast>
  <uv-popup ref="popupRef" :overlay="false" custom-style="background-color: transparent;transform: translateY(-100%);overflow:hidden;">
    <view class="popup">
      <view class="popup-text">搜索结果暂无</view>
      <view class="popup-btn" @click="onBack">返回发现页</view>
    </view>
  </uv-popup>
</template>

<script setup>
  import { ref, inject, reactive, computed, defineProps, watch, defineExpose } from 'vue';
  import { onLoad, onReady, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
  import flow from '@/pages/index/index3Compontents/flow.vue';
  import { getWeek, toastFn } from '@/common/js/fn.js';
  let emits = defineEmits(['goHome']);
  const props = defineProps({
    top: {
      type: Number,
      default: 0
    }
  });
  let toastRef = ref(),
    popupRef = ref();
  let ajax = reactive({
    list: [],
    total: 0,
    totalPage: 1
  });
  let params = reactive({
    currentPage: 1,
    pageSize: 20
  });
  // 请求推荐数据
  const httpHomeRecommend = async type => {
    let { videos, pagination } = await uni.$uv.http.post('/app/home', params);
    ajax.total = pagination.total;
    ajax.totalPage = pagination.totalPage;
    let val = videos.map((r, i) => {
      let videoAddress = '',
        cover = '',
        autoVideo = false,
        teacher,
        title,
        lesson;
      if (r.classify === 'OnlineLesson') {
        videoAddress = r.dynamicCover;
        cover = r.lessonPhoto;
        lesson = {
          grade: r.grade || 1,
          name: r.lessonName,
          lessonNumber: r.lessonItems.length
        };
      } else if (r.classify === 'Video') {
        videoAddress = r.address;
        cover = r.cover;
        teacher = {
          name: r.teacher.username,
          avatar: r.teacher.profilePhoto,
          id: r.teacher.id
        };
        title = r.title;
      } else {
        // 门店视频课  和门店教练课 享有共同数据结构
        videoAddress = r.video.address;
        lesson = {
          grade: r.lesson.grade || 1,
          name: r.lesson.name,
          merchant: r.lesson.merchant?.headquater?.name + ` (${r.lesson.merchant?.name})`,
          time: getWeek(r.issueDate) + ' ' + r.timeDuration
        };
        cover = r.video.cover;
      }
      if (['Lesson', 'MerchantLesson', 'Video'].includes(r.classify) && [0, 1].includes(i)) {
        autoVideo = true;
      }
      if (r.classify === 'OnlineLesson' && i === 0) {
        autoVideo = true;
      }
      return { ...r, autoVideo, videoAddress, cover, teacher, title, lesson };
    });
    tally(val.filter(r => r.autoVideo));
    ajax.list.push(...val);
    if (!videos.length) {
      popupRef.value.open();
      ajax.list.push(...old.value);
    }
  };
  httpHomeRecommend();
  let scrollOldTop = ref(0),
    scrollActive = ref(0);
  let autoVideo = async () => {
    ajax.list.forEach(r => {
      r.autoVideo = false;
    });
    let num = scrollActive.value;
    // 如果是竖着的，那下个也要播放
    if (
      ['Lesson', 'MerchantLesson', 'Video'].includes(ajax.list[num].classify) &&
      ['Lesson', 'MerchantLesson', 'Video'].includes(ajax.list[num + 1].classify)
    ) {
      ajax.list[num + 1].autoVideo = true;
    }
    ajax.list[num].autoVideo = true;
    tally(ajax.list.filter(r => r.autoVideo));
  };
  const tally = val => {
    val.map(async r => {
      await uni.$uv.http.post(
        'app/collect/statistic',
        {
          objectableID: r.id,
          objectableType: r.classify, 
          operationType: 'render' //render 展示 click 查看 share 分享 play 播放完
        },
        {
          custom: { toast: false }
        }
      );
    });
  };
  // 滚动事件，然后加了个防抖
  const onScroll = ({ detail, active }) => {
    scrollOldTop.value = detail.scrollTop;
    scrollActive.value = active;
    autoVideo();
  };
  const onBack = () => {
    popupRef.value.close();
    emits('goHome');
  };
  // 滚动到底部
  const scrolltolower = active => {
    scrollActive.value = active;
    autoVideo();
    if (params.currentPage >= ajax.totalPage) return;
    params.currentPage++;
    httpHomeRecommend();
  };
  let old = ref([]);
  const sonChange = val => {
    old.value = JSON.parse(JSON.stringify(ajax.list));
    ajax.list = [];
    params = { ...val, currentPage: 1, pageSize: 20 };
    httpHomeRecommend();
  };
  defineExpose({ sonChange });
</script>

<style lang="scss" scoped>
  .popup {
    width: 516.279rpx;
    height: 289.535rpx;
    box-shadow: 0px 4px 4px 0px #00000040;
    border-radius: 17.442rpx;
    overflow: hidden;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #000;
    font-size: 20.93rpx;
    &-text {
      margin-top: 73.256rpx;
      margin-bottom: 40.116rpx;
    }
    &-btn {
      background-color: #e5e5e5;
      width: 143.023rpx;
      height: 73.256rpx;
      line-height: 73.256rpx;
      border-radius: 19.186rpx;
      overflow: hidden;
      text-align: center;
    }
  }
</style>
